import { create } from 'zustand';
import { subscribeWithSelector } from 'zustand/middleware';
import queryString from 'query-string';
import type { 
  FilterOptions, 
  UserPermission, 
  DataItem, 
  CircleIndicator, 
  CentralDashboard, 
  TableRow, 
  SidePanelData 
} from '../types/index';

interface DashboardState {
  // 筛选器状态
  filters: FilterOptions;
  availableRegions: string[];
  availableStores: string[];
  availableTimeRanges: string[];
  
  // 用户权限
  userPermission: UserPermission;
  
  // 数据状态
  isLoading: boolean;
  circleIndicators: CircleIndicator[];
  centralDashboard: CentralDashboard;
  tableData: TableRow[];
  leftPanelData: SidePanelData;
  rightPanelData: SidePanelData;
  
  // 筛选器UI状态
  isFilterVisible: boolean;
  
  // 动画状态
  isAnimating: boolean;
  
  // Actions
  setFilters: (filters: FilterOptions) => void;
  setFilterVisible: (visible: boolean) => void;
  loadData: () => void;
  updateCentralRotation: (rotation: number) => void;
  setAnimating: (animating: boolean) => void;
  exportData: () => void;
}

// 模拟用户权限数据
const mockUserPermission: UserPermission = {
  region: ['北京', '上海', '深圳', '广州', '杭州'],
  store: ['北京旗舰店', '上海体验店', '深圳直营店', '广州加盟店', '杭州专卖店'],
  canViewAll: true,
  canExport: true,
  canFilter: true
};

export const useDashboardStore = create<DashboardState>()(
  subscribeWithSelector((set, get) => ({
    // 初始状态
    filters: {
      region: '全部',
      store: '全部',
      timeRange: '今日',
      startDate: '2024-01-01',
      endDate: '2024-12-31'
    },
    
    availableRegions: ['全部', '北京', '上海', '深圳', '广州', '杭州', '南京', '成都', '西安', '武汉'],
    availableStores: ['全部', '旗舰店', '体验店', '直营店', '加盟店', '专卖店'],
    availableTimeRanges: ['今日', '昨日', '近7天', '近30天', '本月', '上月', '本季度', '本年', '自定义'],
    
    userPermission: mockUserPermission,
    
    isLoading: false,
    circleIndicators: [],
    centralDashboard: {
      mainValue: 0,
      mainUnit: '总额',
      subItems: [],
      rotation: 0
    },
    tableData: [],
    leftPanelData: { title: '实时业务监控', items: [] },
    rightPanelData: { title: '数据统计分析', items: [] },
    
    isFilterVisible: false,
    isAnimating: false,
    
    // Actions
    setFilters: (filters: FilterOptions) => {
      set({ filters, isLoading: true });
      
      // 更新URL
      const searchParams = queryString.stringify(filters);
      window.history.pushState({}, '', `?${searchParams}`);
      
      // 重新加载数据
      get().loadData();
    },
    
    setFilterVisible: (visible) => {
      set({ isFilterVisible: visible });
    },
    
    loadData: () => {
      set({ isLoading: true });
      
      // 模拟异步数据加载
      setTimeout(() => {
        const { filters } = get();
        
        // 根据筛选器生成模拟数据
        const mockData = generateMockData(filters);
        
        set({
          isLoading: false,
          circleIndicators: mockData.circleIndicators,
          centralDashboard: mockData.centralDashboard,
          tableData: mockData.tableData,
          leftPanelData: mockData.leftPanelData,
          rightPanelData: mockData.rightPanelData
        });
      }, 500);
    },
    
    updateCentralRotation: (rotation) => {
      set(state => ({
        centralDashboard: {
          ...state.centralDashboard,
          rotation
        }
      }));
    },
    
    setAnimating: (animating) => {
      set({ isAnimating: animating });
    },

    exportData: () => {
      // 模拟导出数据
      alert('导出数据功能待实现');
    }
  }))
);

// 生成模拟数据的函数
function generateMockData(filters: FilterOptions) {
  const baseValue = Math.floor(Math.random() * 5000) + 3000;
  
  const circleIndicators: CircleIndicator[] = [
    {
      id: 'indicator1',
      title: '销售总额',
      value: Math.floor(Math.random() * 2000) + 5000,
      maxValue: 8000,
      unit: '万元',
      color: '#00ffff',
      percentage: Math.floor(Math.random() * 30) + 60
    },
    {
      id: 'indicator2',
      title: '订单数量',
      value: Math.floor(Math.random() * 1000) + 4000,
      maxValue: 6000,
      unit: '笔',
      color: '#00ffff',
      percentage: Math.floor(Math.random() * 25) + 65
    },
    {
      id: 'indicator3',
      title: '客户访问',
      value: Math.floor(Math.random() * 3000) + 8000,
      maxValue: 12000,
      unit: '人次',
      color: '#00ffff',
      percentage: Math.floor(Math.random() * 35) + 55
    },
    {
      id: 'indicator4',
      title: '转化率',
      value: Math.floor(Math.random() * 20) + 75,
      maxValue: 100,
      unit: '%',
      color: '#00ffff',
      percentage: Math.floor(Math.random() * 15) + 75
    }
  ];
  
  const centralDashboard: CentralDashboard = {
    mainValue: baseValue + Math.floor(Math.random() * 2000),
    mainUnit: '总额',
    subItems: [
      { label: '线上销售', value: Math.floor(Math.random() * 15) + 25, color: '#00ffff' },
      { label: '线下销售', value: Math.floor(Math.random() * 10) + 20, color: '#0080ff' },
      { label: '批发业务', value: Math.floor(Math.random() * 8) + 15, color: '#4080ff' },
      { label: '代理销售', value: Math.floor(Math.random() * 10) + 18, color: '#8080ff' },
      { label: '其他渠道', value: Math.floor(Math.random() * 5) + 8, color: '#c080ff' }
    ],
    rotation: 0
  };
  
  const tableData: TableRow[] = Array.from({ length: 15 }, (_, i) => ({
    id: `row-${i}`,
    serialNumber: `${String(i + 1).padStart(2, '0')}`,
    name: [
      '北京旗舰店', '上海体验店', '深圳直营店', '广州加盟店', '杭州专卖店',
      '成都分店', '西安门店', '武汉中心店', '南京精品店', '天津商场店',
      '重庆总店', '郑州连锁店', '长沙旗舰店', '福州体验中心', '济南专营店'
    ][i],
    date: new Date(2024, 2, Math.floor(Math.random() * 28) + 1).toISOString().split('T')[0],
    status: Math.random() > 0.7 ? '异常' : Math.random() > 0.3 ? '正常' : '警告',
    category: [
      '电器, 数码, 家电', '服装, 时尚, 配饰', '食品, 生鲜, 超市', '汽车, 配件, 服务', '图书, 文具, 办公',
      '美妆, 护肤, 个护', '运动, 户外, 健身', '母婴, 玩具, 童装', '家居, 家装, 建材', '医药, 保健, 器械',
      '珠宝, 饰品, 手表', '3C数码, 通讯', '酒类, 茶叶, 饮品', '宠物, 用品, 食品', '金融, 保险, 理财'
    ][i],
    amount: Math.floor(Math.random() * 5000) + 1000
  }));
  
  const leftPanelData: SidePanelData = {
    title: '实时业务监控',
    items: [
      { label: '今日营业额', value: `${(Math.random() * 500 + 200).toFixed(1)}万`, color: '#00ff00' },
      { label: '在线用户', value: `${Math.floor(Math.random() * 5000 + 8000)}人`, color: '#00ffff' },
      { label: '待处理订单', value: `${Math.floor(Math.random() * 200 + 50)}单`, color: '#ffff00' },
      { label: '库存警报', value: `${Math.floor(Math.random() * 10 + 2)}项`, color: '#ff6600' },
      { label: '系统负载', value: `${(Math.random() * 30 + 45).toFixed(1)}%`, color: '#00ffff' },
      { label: '响应时间', value: `${(Math.random() * 100 + 120).toFixed(0)}ms`, color: '#00ff00' },
      { label: '错误率', value: `${(Math.random() * 0.5).toFixed(2)}%`, color: '#ff0000' }
    ]
  };
  
  const rightPanelData: SidePanelData = {
    title: '数据统计分析',
    items: [
      { label: '日同比增长', value: `+${(Math.random() * 15 + 5).toFixed(1)}%`, color: '#00ff00' },
      { label: '周环比增长', value: `+${(Math.random() * 8 + 2).toFixed(1)}%`, color: '#00ff00' },
      { label: '新增客户', value: `${Math.floor(Math.random() * 500 + 200)}人`, color: '#00ffff' },
      { label: '客户满意度', value: `${(Math.random() * 10 + 88).toFixed(1)}%`, color: '#00ff00' },
      { label: '热销商品', value: `${Math.floor(Math.random() * 50 + 120)}款`, color: '#ffff00' },
      { label: '退款率', value: `${(Math.random() * 2 + 1).toFixed(2)}%`, color: '#ff6600' },
      { label: '复购率', value: `${(Math.random() * 20 + 65).toFixed(1)}%`, color: '#00ffff' }
    ]
  };
  
  return {
    circleIndicators,
    centralDashboard,
    tableData,
    leftPanelData,
    rightPanelData
  };
}

// 初始化URL状态同步
export const initializeUrlSync = () => {
  const store = useDashboardStore.getState();
  const urlParams = queryString.parse(window.location.search);
  
  if (Object.keys(urlParams).length > 0) {
    const filters: Partial<FilterOptions> = {};
    
    if (urlParams.region) filters.region = urlParams.region as string;
    if (urlParams.store) filters.store = urlParams.store as string;
    if (urlParams.timeRange) filters.timeRange = urlParams.timeRange as string;
    
    store.setFilters(filters as FilterOptions);
  } else {
    store.loadData();
  }
};

// 订阅状态变化并同步到URL
useDashboardStore.subscribe(
  (state) => state.filters,
  (filters) => {
    const searchParams = queryString.stringify(filters);
    window.history.pushState({}, '', `?${searchParams}`);
  }
); 